package com.zqs.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zqs.bean.ClasscDO;
import com.zqs.bean.StudentDO;
import com.zqs.common.R;
import com.zqs.common.RUtil;
import com.zqs.controller.vo.ClasscPageParam;
import com.zqs.mapper.ClasscMapper;
import com.zqs.mapper.StudentMapper;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 班级管理
 *
 * @author zhangqingshan
 * @date 2024/03/29
 */
@RestController
@RequestMapping("/classc")
@AllArgsConstructor
public class ClasscController {

    final ClasscMapper classcMapper;
    final StudentMapper studentMapper;


    @GetMapping("/list")
    public R<List<ClasscDO>> list() {
        return RUtil.ok(classcMapper.selectList(Wrappers.lambdaQuery(ClasscDO.class).orderByDesc(ClasscDO::getClassNum)));
    }

    @PostMapping("/page")
    public R page(@RequestBody ClasscPageParam param) {
        return RUtil.ok(classcMapper.selectPage(param.getPage(), Wrappers.lambdaQuery(ClasscDO.class)
                .like(StringUtils.isNotBlank(param.getClassName()), ClasscDO::getClassName, param.getClassName()).orderByDesc(ClasscDO::getClassNum)));
    }

    @PostMapping("/add")
    public R add(@RequestParam("className") String className) {
        if (null != classcMapper.selectOne(Wrappers.lambdaQuery(ClasscDO.class).eq(ClasscDO::getClassName, className))) {
            return RUtil.fail("此班级已存在");
        }
        ClasscDO csDO = new ClasscDO();
        csDO.setClassName(className);
        int i = classcMapper.insert(csDO);
        if (i == 1) {
            return RUtil.ok(null);
        } else {
            return RUtil.fail("新增异常");
        }
    }

    @PostMapping("/edit")
    public R edit(@RequestBody @Validated ClasscDO csDO) {
        if (null == classcMapper.selectById(csDO.getClassNum())) {
            return RUtil.fail("此班级不存在");
        }

        int i = classcMapper.updateById(csDO);
        if (i == 1) {
            return RUtil.ok(null);
        } else {
            return RUtil.fail("修改异常");
        }
    }

    @DeleteMapping("/del/{classNum}")
    public R del(@PathVariable("classNum") Integer classNum) {
        if (null == classcMapper.selectById(classNum)) {
            return RUtil.fail("此班级不存在");
        }
        Long count = studentMapper.selectCount(Wrappers.lambdaQuery(StudentDO.class).eq(StudentDO::getClassNum, classNum));
        if (count > 0) {
            return RUtil.fail("此班级有学生，无法删除");
        }
        int i = classcMapper.deleteById(classNum);
        if (i == 1) {
            return RUtil.ok(null);
        } else {
            return RUtil.fail("删除异常");
        }
    }


}
